//
//  TeamInfoViewController.m
//  SportsApp
//
//  Created by Matthew Moritz on 2012-11-29.
//  Copyright (c) 2012 Matthew Moritz. All rights reserved.
//

#import "TeamInfoViewController.h"
#import "GameTableViewCell.h"
#import "JsonData.h"

@interface TeamInfoViewController ()<UITableViewDelegate, UITableViewDataSource> {
    IBOutlet UITableView *infoTable;
}
@end

@implementation TeamInfoViewController

@synthesize seasonLabel;

@synthesize fullName;
@synthesize teamName;
@synthesize season;

@synthesize teamImageView;
@synthesize teamNameLabel;

@synthesize values;
@synthesize categories;

@synthesize infoTable;
@synthesize streakEntries;

@synthesize record;
@synthesize streak;

@synthesize statsTable;
@synthesize gameEntries;

@synthesize seasonStepper;

/* Season Totals */
@synthesize totalgoalsForLabel;
@synthesize totalgoalsAgainstLabel;
@synthesize totalSogLabel;
@synthesize totalFaceoffsWonLabel;

/* ********* */

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {}
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    teamName = [self getTeamName:fullName]; /* Get team name for query. */
    season = @"2011";                       /* Set default season to 2011. */
    
    teamNameLabel.text = fullName;                      /* Set team name label. */
    teamImageView.image = [self getTeamImage:fullName]; /* Set team logo image. */
    seasonLabel.text = [self createSeasonLabel:season]; /* Set season label */
    
    JsonData *data = [[JsonData alloc] init]; /* Create a JsonData object. */
    
    gameEntries = [self populateStatsTable:data:season];
    [self populateInfoTable:data:gameEntries:season];
    [self calculateSeasonTotals:gameEntries];
    
    /* Reload the tables. */
    [statsTable reloadData];
    [infoTable reloadData];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 * Given a team's full name, this method will return the last part
 * of the team name.
 *
 * For example: Calgary Flames -> Flames
 *
 * NOTE: There are 3 cases that need to be handled differently
 *       than the rest of the teams. This is because there are
 *       two parts to the name.
 */
- (NSString *)getTeamName:(NSString *)name {
    
    NSString *team;
    
    // 3 special cases.
    if(name == @"Toronto Maple Leafs") {
        team = @"Maple+Leafs";
    }
    else if(name == @"Columbus Blue Jackets") {
        team = @"Blue+Jackets";
    }
    else if(name == @"Detroit Red Wings") {
        team = @"Red+Wings";
    }
    // typical case.
    else {
        NSArray *array = [name componentsSeparatedByString:@" "];
        int size = [array count] - 1;
        
        team = [array objectAtIndex:size];
    }
    
    return team;
}

/**
 * Given a team's full name, this method will return the logo of
 * the specified team.
 *
 * For example: Calgary Flames -> calgaryflames.png
 *
 */
- (UIImage *)getTeamImage:(NSString *)name {
    
    NSString *imageName = [name stringByReplacingOccurrencesOfString:@" " withString:@""]; /* remove spaces. */
    
    imageName = [imageName lowercaseString];                 /* Change to lowercase. */
    imageName = [imageName stringByAppendingString:@".png"]; /* Add .png to the end. */
    
    return [UIImage imageNamed: imageName];
}

/**
 * Creates a season label, which displays the starting and ending year of the season.
 *
 * For example: "2011 - 2012"
 *
 */
-(NSString *)createSeasonLabel:(NSString *)currentSeason {
    
    int startYear = [currentSeason intValue];
    int endYear   = [currentSeason intValue] + 1;
    
    return [NSString stringWithFormat:@"%d - %d", startYear, endYear];
}

/**
 * Creates a NSMutableDictionary that will populate the stats table.
 *
 */
-(NSMutableDictionary *)populateStatsTable:(JsonData *)json:(NSString *)currentSeason {
    
    NSURL *url = [json buildTeamURL:teamName:season]; /* Build URL */
    return [json executeQuery:url];            /* Execute query */
}

-(void)populateInfoTable:(JsonData *)json:(NSDictionary *)entries:(NSString *)currentSeason {
    
    record = [self calculateRecord:entries];
    streak = [self calculateLongestStreak:json:currentSeason];
}

/**
 * Calculates the team's record by adding up the number of wins and losses.
 *
 * Returns a string in the form of "wins - losses".
 */
-(NSString *)calculateRecord:entries {
    
    int wins = 0;
    int losses = 0;
    
    for(int i=0; i < [entries[@"goals"] count]; i++) {
        
        if([[entries[@"goals"] objectAtIndex:i] intValue] > [[entries[@"o:goals"] objectAtIndex:i] intValue]) {
            wins++;
        } else {
            losses++;
        }
    }
    
    return [NSString stringWithFormat:@"%d - %d", wins, losses];
}

/**
 * Creates and runs a query that gets all of the streaks for a team's season.
 * Returns the maximum streak for that season.
 *
 */
-(NSString *)calculateLongestStreak:(JsonData *)json:(NSString *)currentSeason {
    
    NSString *streakString = [@"http://api.sportsdatabase.com/nhl/query.json?sdql=streak%40team%3D" stringByAppendingString:teamName];
    streakString = [streakString stringByAppendingString:@"+and+season%3D"];
    streakString = [streakString stringByAppendingString:currentSeason];
    streakString = [streakString stringByAppendingString:@"&output=json&api_key=kw48158"];
    
    NSURL * streakUrl = [NSURL URLWithString:streakString];
    streakEntries = [json executeQuery:streakUrl];
    
    int max = -100;
    for(NSNumber *n in streakEntries[@"streak"]) {
        if([n isKindOfClass:[NSNumber class]]) {
            if([n intValue] > max) {
                max = [n intValue];
            }
        }
    }
    
    return [NSString stringWithFormat:@"%d", max];
}

/**
 * Calculates the season totals of the selected team
 *
 */
-(void)calculateSeasonTotals:entries {
    
    int goalsFor = 0;
    int goalsAgainst = 0;
    int faceoffsWon = 0;
    int shotsOnGoal = 0;
    
    NSString *gF, *gA, *fW, *sG;
    
    for(int i=0; i < [entries[@"goals"] count]; i++) {
    
        gF = [NSString stringWithFormat:@"%@", [entries[@"goals"] objectAtIndex:i]];
        gA = [NSString stringWithFormat:@"%@", [entries[@"o:goals"] objectAtIndex:i]];
        fW = [NSString stringWithFormat:@"%@", [entries[@"faceoffs won"] objectAtIndex:i]];
        sG = [NSString stringWithFormat:@"%@", [entries[@"shots on goal"] objectAtIndex:i]];
        
        /* goals for */
        if ([gF rangeOfString:@"null"].location == NSNotFound)
            goalsFor += [gF intValue];
        /* goals against */
         if ([gA rangeOfString:@"null"].location == NSNotFound)
            goalsAgainst += [gA intValue];
        /* faceoffs won */
         if ([fW rangeOfString:@"null"].location == NSNotFound)
            faceoffsWon += [fW intValue];
        /* shots on goal */
         if ([sG rangeOfString:@"null"].location == NSNotFound)
            shotsOnGoal += [sG intValue];
    }

    /* set the labels */
    totalgoalsForLabel.text = [NSString stringWithFormat:@"%d", goalsFor];
    totalgoalsAgainstLabel.text = [NSString stringWithFormat:@"%d", goalsAgainst];
    totalSogLabel.text = [NSString stringWithFormat:@"%d", shotsOnGoal];
    totalFaceoffsWonLabel.text = [NSString stringWithFormat:@"%d", faceoffsWon];
}




#pragma mark UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(tableView == infoTable) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InfoCell"];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"InfoCell"];
        }
        
        int row = indexPath.row;
        
        @try {
            
            if(row == 0) {
                cell.textLabel.text = @"Record";
                cell.detailTextLabel.text = record;
            }
            else {
                cell.textLabel.text = @"Longest Win Streak";
                cell.detailTextLabel.text = streak;
            }
            
            
        }
        @catch (NSException * e) {
            return NULL;
        }
        
        return cell;
    }
    else if(tableView == statsTable) {
        
        GameTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GameCell"];
        
        if (cell == nil) {
            cell = [[GameTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"GameCell"];
        }
        
        int row = indexPath.row;
        
        @try {
            /*
             * Add date
             */
            NSString *year  = [[[gameEntries[@"date"] objectAtIndex:row] stringValue] substringWithRange:NSMakeRange(0, 4)];
            NSString *month = [[[gameEntries[@"date"] objectAtIndex:row] stringValue] substringWithRange:NSMakeRange(4, 2)];
            NSString *day   = [[[gameEntries[@"date"] objectAtIndex:row] stringValue] substringWithRange:NSMakeRange(6, 2)];
            NSString *date  = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
            
            if(date != nil)
                cell.dateLabel.text = date;
            else
                cell.dateLabel.text = @"Not Available";
            
            /*
             * Add opponent
             */
            NSString *opponent = [gameEntries[@"o:team"] objectAtIndex:row];
            
            if(opponent != nil)
                cell.opponentLabel.text = opponent;
            else
                cell.opponentLabel.text = @"Not Available";
            
            /*
             * Add win/loss and score
             */
            NSNumber *goals         = [gameEntries[@"goals"] objectAtIndex:row];
            NSNumber *opponentGoals = [gameEntries[@"o:goals"] objectAtIndex:row];
            
            if([goals intValue] > [opponentGoals intValue]) {
                cell.winLossLabel.text = @"W";
            }
            else {
                cell.winLossLabel.text = @"L";
            }
            cell.scoreLabel.text = [NSString stringWithFormat:@"%@ - %@", goals, opponentGoals];
            
            /*
             * Add site
             */
            NSString *site = [gameEntries[@"site"] objectAtIndex:row];
            
            if([site isEqual:@"home"])
                cell.siteLabel.text = @"Home";
            else if([site isEqual:@"away"])
                cell.siteLabel.text = @"Away";
            else
                cell.siteLabel.text = @"Not Available";
            
            /*
             * Add shots on goal
             */
            NSNumber *shots         = [gameEntries[@"shots on goal"] objectAtIndex:row];
            NSNumber *opponentShots = [gameEntries[@"o:shots on goal"] objectAtIndex:row];
            NSString *shotsOnGoal   = [NSString stringWithFormat:@"%@ - %@", shots, opponentShots];
            
            if ([shotsOnGoal rangeOfString:@"null"].location == NSNotFound)
                cell.sogLabel.text = shotsOnGoal;
            else
                cell.sogLabel.text = @"---";
            
            /*
             * Add faceoffs won
             */
            NSNumber *faceoffs         = [gameEntries[@"faceoffs won"] objectAtIndex:row];
            NSNumber *opponentFaceoffs = [gameEntries[@"o:faceoffs won"] objectAtIndex:row];
            NSString *faceoffsWon      = [NSString stringWithFormat:@"%@ - %@", faceoffs, opponentFaceoffs];
            
            if ([faceoffsWon rangeOfString:@"null"].location == NSNotFound)
                cell.fwLabel.text = faceoffsWon;
            else
                cell.fwLabel.text = @"---";
        }
        @catch (NSException * e) {
            return NULL;
        }
        
        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(tableView == infoTable)
        return 2;
    else {
        // return the number of games.
        return [gameEntries[@"date"] count];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (IBAction)stepperChanged:(UIStepper *)sender {
    
    season = [NSString stringWithFormat:@"%0.0f",sender.value]; /* Update the season. */
    
    JsonData *data = [[JsonData alloc] init]; /* Create a JsonData object. */
    
    gameEntries = [self populateStatsTable:data:season];
    [self populateInfoTable:data:gameEntries:season];
    
    /* Reload the tables. */
    
    [self calculateSeasonTotals:gameEntries];
    
    [statsTable reloadData];
    [infoTable reloadData];
}
@end
